package com.lgCore.common;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 网关所需参数配置
 */
public class IpDataEntity implements Serializable {
    static {
        try {
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.submit(()->{
                try {
                    while(true){
                        IpDataEntity.removeData();
                        //每10分钟清空一次
                        Thread.sleep(10*60*1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //收集ping的通IP
    public static volatile Set<String> pingIp = new HashSet<>();
    //收集ping不通IP
    public static volatile Set<String> unPingIp = new HashSet<>();

    /**
     * 每十分钟清空一次
     * 避免出现偶尔的网络抖动导致运行不了
     */
    public static void removeData(){
        pingIp.clear();
        unPingIp.clear();
    }
    /**
     * 添加能ping通 ip
     */
    public static void addPingIdData(String ip){
        pingIp.add(ip);
        unPingIp.remove(ip);
    }
    /**
     * 添加不能ping通 ip
     */
    public static void addUnPingIdData(String ip){
        unPingIp.add(ip);
        pingIp.remove(ip);
    }

    /**
     * 是否能ping通
     * @param ip
     * @return
     */
    public static boolean isPing(String ip){
        if (IpDataEntity.pingIp.contains(ip)) {
            return true;
        } else if (IpDataEntity.unPingIp.contains(ip)) {
            return false;
            //注销实例
//              executeDeregisterInstance(serviceName,namingService,instance);
        } else {
            if (validatorPingIP(ip)) {
                //能ping通
                IpDataEntity.addPingIdData(ip);
                return true;
            } else {
                //ping不通
                IpDataEntity.addUnPingIdData(ip);
                return false;
            }
        }
    }


    /**
     * 校验ip是否能ping通
     *
     * @param ip
     * @return
     */
    public static boolean validatorPingIP(String ip) {
        try {

            InetAddress address = InetAddress.getByName(ip);
            return address.isReachable(50);
        } catch (UnknownHostException e) {
            System.err.println("Unable to lookup web.mit.edu");
        } catch (IOException e) {
            System.err.println("Unable to reach web.mit.edu");
        }
        return false;
    }
}
